/**
 * @p.md
 * 
 * WasmPersistence 模块，提供与 Go 后端集成的持久化能力
 */

import { WasmBridge, WasmBridgeFactory } from './wasmBridge';

/**
 * 事件封装
 */
export interface PersistedEvent {
  eventIndex: number;
  persistenceID: string;
  eventData: any;
}

/**
 * 快照封装
 */
export interface Snapshot {
  persistenceID: string;
  snapshotIndex: number;
  snapshotData: any;
}

/**
 * WASM 持久化提供者接口，定义持久化操作
 */
export interface WasmPersistenceProvider {
  /**
   * 获取事件
   * @param persistenceID 持久化 ID
   * @param indexStart 起始索引
   * @param indexEnd 结束索引
   * @param callback 回调函数，接收事件数组
   */
  getEvents(
    persistenceID: string,
    indexStart: number,
    indexEnd: number,
    callback: (events: PersistedEvent[]) => void
  ): void;

  /**
   * 持久化事件
   * @param persistenceID 持久化 ID
   * @param eventIndex 事件索引
   * @param event 事件数据
   * @param callback 回调函数，接收是否成功
   */
  persistEvent(
    persistenceID: string,
    eventIndex: number,
    event: any,
    callback: (success: boolean) => void
  ): void;

  /**
   * 获取最新快照
   * @param persistenceID 持久化 ID
   * @param callback 回调函数，接收快照
   */
  getLatestSnapshot(
    persistenceID: string,
    callback: (snapshot: Snapshot | null) => void
  ): void;

  /**
   * 持久化快照
   * @param persistenceID 持久化 ID
   * @param snapshotIndex 快照索引
   * @param snapshot 快照数据
   * @param callback 回调函数，接收是否成功
   */
  persistSnapshot(
    persistenceID: string,
    snapshotIndex: number,
    snapshot: any,
    callback: (success: boolean) => void
  ): void;

  /**
   * 删除事件
   * @param persistenceID 持久化 ID
   * @param inclusiveToIndex 删除到的索引（包含）
   * @param callback 回调函数，接收是否成功
   */
  deleteEvents(
    persistenceID: string,
    inclusiveToIndex: number,
    callback: (success: boolean) => void
  ): void;

  /**
   * 删除快照
   * @param persistenceID 持久化 ID
   * @param inclusiveToIndex 删除到的索引（包含）
   * @param callback 回调函数，接收是否成功
   */
  deleteSnapshots(
    persistenceID: string,
    inclusiveToIndex: number,
    callback: (success: boolean) => void
  ): void;
}

/**
 * 基于 WASM 的持久化提供者实现
 */
export class WasmPersistenceProviderImpl implements WasmPersistenceProvider {
  private bridge: WasmBridge;

  /**
   * 构造函数
   * @param bridge WASM 桥接器
   */
  constructor(bridge?: WasmBridge) {
    this.bridge = bridge || WasmBridgeFactory.getInstance();
  }

  /**
   * 获取持久化事件
   */
  getEvents(
    persistenceID: string,
    indexStart: number,
    indexEnd: number,
    callback: (events: PersistedEvent[]) => void
  ): void {
    const callbackId = this.bridge.createCallback((eventsJson: string) => {
      try {
        const events = JSON.parse(eventsJson) as PersistedEvent[];
        callback(events);
      } catch (error) {
        console.error('Error parsing events:', error);
        callback([]);
      } finally {
        this.bridge.releaseCallback(callbackId);
      }
    });

    this.bridge.invokeGoFunction(
      'PersistenceGetEvents',
      persistenceID,
      indexStart,
      indexEnd,
      callbackId
    ).catch(error => {
      console.error('Failed to get events:', error);
      this.bridge.releaseCallback(callbackId);
      callback([]);
    });
  }

  /**
   * 持久化事件
   */
  persistEvent(
    persistenceID: string,
    eventIndex: number,
    event: any,
    callback: (success: boolean) => void
  ): void {
    const callbackId = this.bridge.createCallback((result: boolean) => {
      callback(result);
      this.bridge.releaseCallback(callbackId);
    });

    this.bridge.invokeGoFunction(
      'PersistencePersistEvent',
      persistenceID,
      eventIndex,
      JSON.stringify(event),
      callbackId
    ).catch(error => {
      console.error('Failed to persist event:', error);
      this.bridge.releaseCallback(callbackId);
      callback(false);
    });
  }

  /**
   * 获取最新快照
   */
  getLatestSnapshot(
    persistenceID: string,
    callback: (snapshot: Snapshot | null) => void
  ): void {
    const callbackId = this.bridge.createCallback((snapshotJson: string) => {
      try {
        if (!snapshotJson) {
          callback(null);
          return;
        }
        const snapshot = JSON.parse(snapshotJson) as Snapshot;
        callback(snapshot);
      } catch (error) {
        console.error('Error parsing snapshot:', error);
        callback(null);
      } finally {
        this.bridge.releaseCallback(callbackId);
      }
    });

    this.bridge.invokeGoFunction(
      'PersistenceGetLatestSnapshot',
      persistenceID,
      callbackId
    ).catch(error => {
      console.error('Failed to get latest snapshot:', error);
      this.bridge.releaseCallback(callbackId);
      callback(null);
    });
  }

  /**
   * 持久化快照
   */
  persistSnapshot(
    persistenceID: string,
    snapshotIndex: number,
    snapshot: any,
    callback: (success: boolean) => void
  ): void {
    const callbackId = this.bridge.createCallback((result: boolean) => {
      callback(result);
      this.bridge.releaseCallback(callbackId);
    });

    this.bridge.invokeGoFunction(
      'PersistencePersistSnapshot',
      persistenceID,
      snapshotIndex,
      JSON.stringify(snapshot),
      callbackId
    ).catch(error => {
      console.error('Failed to persist snapshot:', error);
      this.bridge.releaseCallback(callbackId);
      callback(false);
    });
  }

  /**
   * 删除事件
   */
  deleteEvents(
    persistenceID: string,
    inclusiveToIndex: number,
    callback: (success: boolean) => void
  ): void {
    const callbackId = this.bridge.createCallback((result: boolean) => {
      callback(result);
      this.bridge.releaseCallback(callbackId);
    });

    this.bridge.invokeGoFunction(
      'PersistenceDeleteEvents',
      persistenceID,
      inclusiveToIndex,
      callbackId
    ).catch(error => {
      console.error('Failed to delete events:', error);
      this.bridge.releaseCallback(callbackId);
      callback(false);
    });
  }

  /**
   * 删除快照
   */
  deleteSnapshots(
    persistenceID: string,
    inclusiveToIndex: number,
    callback: (success: boolean) => void
  ): void {
    const callbackId = this.bridge.createCallback((result: boolean) => {
      callback(result);
      this.bridge.releaseCallback(callbackId);
    });

    this.bridge.invokeGoFunction(
      'PersistenceDeleteSnapshots',
      persistenceID,
      inclusiveToIndex,
      callbackId
    ).catch(error => {
      console.error('Failed to delete snapshots:', error);
      this.bridge.releaseCallback(callbackId);
      callback(false);
    });
  }
}

/**
 * WASM 持久化工厂
 */
export class WasmPersistenceFactory {
  private static instance: WasmPersistenceProviderImpl;

  /**
   * 获取 WASM 持久化提供者实例
   * @param bridge 可选的 WASM 桥接器实例
   * @returns WASM 持久化提供者
   */
  static getInstance(bridge?: WasmBridge): WasmPersistenceProvider {
    if (!WasmPersistenceFactory.instance) {
      WasmPersistenceFactory.instance = new WasmPersistenceProviderImpl(bridge);
    }
    return WasmPersistenceFactory.instance;
  }
} 